package controller;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import javax.swing.JFrame;
import util.Arithmetic;

/**
 * Responsible for maintain the correct maximum and minimum sizes for the Window.
 * Due to limitations in Swing, a maximum size cannot be completely enforced as
 * most OSes do not allow it. However, it will be enforced when maximising.
 */
public class WindowController extends ComponentAdapter {

	public static final Dimension MIN_SIZE = new Dimension(320, 240);
	public static final Dimension MAX_SIZE = new Dimension(640, 480);

	@Override
	public void componentResized(ComponentEvent e) {
		Component c = e.getComponent();

		if(!(c instanceof JFrame)) return;

		JFrame frame = (JFrame)c;

		//Border of the window does not count towards actual size of content.
		Insets insets = frame.getInsets();
		int width = frame.getWidth() - insets.left - insets.right;
		int height = frame.getHeight() - insets.top - insets.bottom;

		Dimension newSize = new Dimension(width, height);

		if(!Arithmetic.containsDimension(newSize, MIN_SIZE)) {
			//Window is smaller than minimum, set it to minimum.
			frame.setSize(Arithmetic.addInsets(MIN_SIZE, insets));
		} else if(!Arithmetic.containsDimension(MAX_SIZE, newSize)) {
			//Window is larger than maximum, set it to maximum.
			frame.setSize(Arithmetic.addInsets(MAX_SIZE, insets));
		}

	}

}
